package com.itheima.security;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/20 17:38
 * @Description:
 */
public class UserService implements UserDetailsService {
    @Autowired
	BCryptPasswordEncoder passwordEncoder;
	/**
	 *  @描述：通过用户名查询用户
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 使用Map模拟数据库，放入两个用户对象
		Map map = new HashMap();
		User user1= new User();
		user1.setUsername("admin");
		user1.setPassword(passwordEncoder.encode("admin"));
		map.put(user1.getUsername(),user1);
		User user2= new User();
		user2.setUsername("xiaoming");
		user2.setPassword(passwordEncoder.encode("xiaoming"));
		map.put(user2.getUsername(),user2);
		Object o = map.get(username);
		if(ObjectUtils.isEmpty(o)){
			return null;
		}

		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		if("admin".equals(((User)o).getUsername())) {
			grantedAuthorities.add(new SimpleGrantedAuthority("add"));
		}
		grantedAuthorities.add(new SimpleGrantedAuthority("delete"));
		grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

		return new org.springframework.security.core.userdetails.User(username, ((User)o).getPassword(), grantedAuthorities);
	}
}
